<template>
  <el-dialog v-if="load" title="广告授权" v-model="visible" append-to-body width="500px" @close="handleClose">
    <el-form label-position="top">
      <el-form-item label="开发者账号" :error="form.message">
        <VSelect v-model="form.ad_id" placeholder="请选择" :options="options.ad_developer" class="w-full" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">授 权</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from './api'
import { ElMessage } from 'element-plus'
import { on, off } from "@/utils/dom";
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({})

const emit = defineEmits(['close', 'success'])

// 打开弹窗
const open = async (shop_id) => {
  form.value = { shop_id, ad_id: '', message: '' }
  if (props.options) {
    const {ad_developer} = props.options
    if (ad_developer && Array.isArray(ad_developer) && ad_developer.length > 0) {
      form.value.ad_id = ad_developer[0].value
    }
  }
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

// 授权
const handleMessage = ({ data }) => {
  if (data.refresh_token) {
    form.value = { ...form.value, ...data }
  }
  close()
  off(window, 'message', handleMessage)
}

let win = null
const handleClone = () => {
  if (data) {
    ElMessage.success('授权成功')
  } else {
    ElMessage.error('授权失败')
  }
  off(win, 'beforeunload', handleClone)
  win = null
}

// 提交
const submit = () => {
  const { ad_id, shop_id } = form.value
  if (!ad_id) {
    form.value.message = '不能为空'
    return
  } else {
    form.value.message = ''
  }
  loadings.submit = true
  api.adLink({ ad_id }).then(res => {
    win = window.open(
      res.data.auth_link + encodeURIComponent(`${window.location.origin}/auth?ad_id=${ad_id}&type=amazonAd${shop_id ? '&shop_id='+shop_id : ''}`),
      '_blank',
      'height=700, width=1200, top=200, left=300,toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no'
    )
    loadings.submit = false
    on(window, 'message', handleMessage)
    on(win, 'beforeunload', handleClone)
  })
}

defineExpose({ open })
</script>